package org.september.pisces.user.permission.service;

import java.util.HashMap;
import java.util.Map;

import org.september.core.exception.BusinessException;
import org.springframework.stereotype.Service;

@Service
public class UserPwdErrorCheckService {

	//默认半小时后可以重试
	private long discardTime = 1800*1000;
	
	private static int MaxRetryTimes =6 ;
	//ip-->登录错误时间列表
	private Map<String,ErrorInfo> errMap = new HashMap<>();
	
	private class ErrorInfo{
		private Long lastestLoginTime;
		private int errorTimes;
	}
	
	public boolean isOverLimits(String ip) {
		if(errMap.containsKey(ip)) {
			ErrorInfo err = errMap.get(ip);
			if(err.errorTimes>=MaxRetryTimes) {
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
	}
	public void addErrorTime(String ip) {
		if(errMap.containsKey(ip)) {
			ErrorInfo err = errMap.get(ip);
			err.errorTimes = err.errorTimes+1;
		}else {
			ErrorInfo err = new ErrorInfo();
			err.lastestLoginTime = System.currentTimeMillis();
			err.errorTimes=1;
			errMap.put(ip, err);
		}
	}
	
	public void pass(String ip) {
		errMap.remove(ip);
	}
	public void removeOverTimeErrorInfo(String ip) {
		if(errMap.containsKey(ip)) {
			ErrorInfo err = errMap.get(ip);
			if( (System.currentTimeMillis() - err.lastestLoginTime) > discardTime) {
				errMap.remove(ip);
			}
		}
	}
	
	public int getErrorTimes(String ip) {
		if(errMap.containsKey(ip)) {
			return errMap.get(ip).errorTimes;
		}else {
			return 0;
		}
	}
	
	public int getLeftRetryTimes(String ip) {
		return MaxRetryTimes - getErrorTimes(ip);
	}
	
	public void checkPwdErrorLimits(String ip) {
		removeOverTimeErrorInfo(ip);
		if(isOverLimits(ip)) {
			throw new BusinessException("重试次数超过6次，请半小时后重试登录");
		}else {
			addErrorTime(ip);
			int left = getLeftRetryTimes(ip);
			throw new BusinessException("用户名或密码错误,还可以尝试"+left+"次");
		}
	}
}

